package com.msblearn.C_006;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.locks.LockSupport;

/**
 * 贼简单:但还是需要和countdownlatch一样。使用两把锁。
 */
public class T006_LockSupport {
    //ArrayList是线程不安全的。
    List list = new ArrayList();
    static Thread t1 = null, t2 = null;

    public void add(Object o) {
        list.add(o);
    }

    public int size() {
        return list.size();
    }

    public static void main(String[] args) {
        T006_LockSupport support = new T006_LockSupport();


        t2 = new Thread(() -> {
            System.out.println("T2启动");
            if (support.size() != 5) {
                LockSupport.park();
            }
            //启动t1
            LockSupport.unpark(t1);
            System.out.println("T2结束");
        });
        t2.start();
        t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                support.add(new Object());
                System.out.println("add " + i);
                if (support.size() == 5) {
                    LockSupport.unpark(t2);
                    //阻塞t1
                    LockSupport.park();
                }
            }
        });
        t1.start();
    }
}


